package com.example.binpacking.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/pelicanpsyc")
public class ProxyController {
    @Value("${model.server.url}")
    private String modelServerUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    @PostMapping("/api/prompt")
    public ResponseEntity<String> prompt(@RequestBody Map<String, String> payload) {
        String input = payload.get("prompt");
        Map<String, String> requestPayload = new HashMap<>();
        requestPayload.put("input", input);

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestPayload, headers);

        log.info("Sending request to model server: {}", modelServerUrl);
        log.info("Request payload: {}", requestPayload);

        try {
            return restTemplate.postForEntity(modelServerUrl, entity, String.class);
        } catch (HttpClientErrorException e) {
            log.error("Client error: {}", e.getMessage());
            return ResponseEntity.status(e.getStatusCode()).body(e.getMessage());
        } catch (HttpServerErrorException e) {
            log.error("Server error: {}", e.getMessage());
            return ResponseEntity.status(e.getStatusCode()).body(e.getMessage());
        } catch (Exception e) {
            log.error("Unexpected error: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
        }
    }

}
